package org.wattdepot.cli.command;

import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.cli.processor.CommandLineInterface;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * TotalGenerated Class.
 * 
 * @author Remy Baumgarten
 * @author Kevin Chiogioji
 */
public class TotalGenerated extends CommandLineInterface implements WattDepotCliCommand {

  /**
   * Command 2.9 - Returns the total amount of carbon (or energy) generated (or consumed) by this
   * source for the given day. The sampling interval indicates how to generate the curve of carbon
   * (or energy) data points.
   * 
   * @param args -
   * @return -
   */
  public String doCommand(List<String> args) {

    String type = args.get(0);
    String source = args.get(1);
    String day = args.get(2);
    int minutes;
    String result;
    try {
      if (type.equalsIgnoreCase("carbon") || type.equalsIgnoreCase("energy")) {
        XMLGregorianCalendar startTime = null;
        XMLGregorianCalendar endTime = null;
        startTime = Tstamp.makeTimestamp(day);
        endTime = Tstamp.incrementDays(startTime, 1);
        minutes = Integer.parseInt(args.get(3));
        double total = 0;
        if (type.equalsIgnoreCase("carbon")) {
          total = client.getCarbonEmitted(source, startTime, endTime, minutes);
        }
        else if (type.equalsIgnoreCase("energy")) {
          total = client.getEnergyGenerated(source, startTime, endTime, minutes);
        }
        result = String.valueOf(total);
      }
      else {
        return "Invalid Command";
      }
    }
    catch (NumberFormatException nfe) {
      return "Interval is not correct";
    }
    catch (MiscClientException mce) {
      return errorClient;
    }
    catch (BadXmlException bxe) {
      return errorXML;
    }
    catch (ResourceNotFoundException rnfe) {
      return error404;
    }
    catch (NotAuthorizedException nae) {
      return error401;
    }
    catch (Exception e) {
      return errorTimeStamp;
    }
    return result;
  }
}
